using System;
using System.Collections.Generic;
using System.Text;
using NBusiness.CodeDom;
using NBusiness.ESharp.Compiler;
using NBusiness.CodeDom.Compiler;

namespace NBusiness.ESharp
{
    [Serializable]
    public class ESharpAction : EntityAction
    {
        protected override void Attach()
        {
            //nothing
        }

        protected override void InitializeAssignmentLogic()
        {
            //action [name] on [type].[type] when [actiontype] [async];
            //action [name] on [type].[type] when [actiontype];
            //action [name] when [actiontype] [async];
            //action [name] when [actiontype];
            //action [name];

            //name
            Assignments.Add(new AssignmentLogic( 
                ESharpEntityElementTypes.ActionName,
                new AssignmentLogicHandler(AssignName) ));

            //as
            Assignments.Add(new AssignmentLogic( ESharpEntityElementTypes.ActionOn ));

            //type
            Assignments.Add(new AssignmentLogic( 
                ESharpEntityElementTypes.ActionType,
                new AssignmentLogicHandler(AssignType) ));

            //type join
            Assignments.Add(new AssignmentLogic( ESharpEntityElementTypes.ActionTypeJoin ));

            //when
            Assignments.Add(new AssignmentLogic( ESharpEntityElementTypes.ActionWhen ));

            //when type
            Assignments.Add(new AssignmentLogic( 
                ESharpEntityElementTypes.ActionWhenType,
                new AssignmentLogicHandler(AssignWhenType) ));

            //async
            Assignments.Add(new AssignmentLogic( 
                ESharpEntityElementTypes.ActionAsync,
                new AssignmentLogicHandler(AssignAsync) ));

            //;
            Assignments.Add(new AssignmentLogic(
                ESharpEntityElementTypes.StatementEnd,
                PostAssignmentAction.Stop ));

            Assignments.Add(new AssignmentLogic( ESharpEntityElementTypes.WhiteSpace ));
            Assignments.Add(new AssignmentLogic( ESharpEntityElementTypes.Comment ));
        }

        private void AssignName(object sender, AssignmentLogicEventArgs e)
        {
            Name = e.Elements.Peek().Value;
        }
        private void AssignType(object sender, AssignmentLogicEventArgs e)
        {
            On = (On == null ? e.Elements.Peek().Value : On + "." + e.Elements.Peek().Value);            
        }
        private void AssignWhenType(object sender, AssignmentLogicEventArgs e)
        {
            When = (EntityActionType)Enum.Parse(typeof(EntityActionType), e.Elements.Peek().Value, true);
        }
        private void AssignAsync(object sender, AssignmentLogicEventArgs e)
        {
            Async = true;
        }

        public override string ToString()
        {
            return Name;
        }
    }
}
